package first.group.ssh.gui.model;

import first.group.ssh.gui.dialog.ConnectDialog;
import first.group.ssh.gui.state.MainState;
import first.group.ssh.gui.state.SshSession;
import first.group.ssh.gui.util.DocumentUtil;
import first.group.ssh.gui.util.NumberFilter;
import java.net.InetSocketAddress;
import javax.swing.JOptionPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class ConnectModel {

    private MainState state = MainState.getInstance();
    private final PlainDocument hostNameDocument = new PlainDocument();
    private final PlainDocument portDocument = new PlainDocument();
    private ConnectDialog dialog = null;

    public ConnectModel() {
        portDocument.setDocumentFilter(new NumberFilter());
        try {
            portDocument.insertString(0, "22", null);
        } catch (BadLocationException ex) {
        }
    }

    public void bindToFrame(ConnectDialog dialog) {
        if (this.dialog != null) {
            throw new IllegalStateException("This model is already bound to a frame");
        }
        this.dialog = dialog;
        dialog.hostField.setDocument(hostNameDocument);
        dialog.portField.setDocument(portDocument);
    }

    public void doConnect() {
        InetSocketAddress address = null;
        try {
            var hostName = DocumentUtil.getText(hostNameDocument);
            var port = DocumentUtil.getText(portDocument);
            if (hostName != null && port != null) {
                address = new InetSocketAddress(hostName, Integer.parseInt(port));
            }
        } catch (NumberFormatException ex) {
        }
        if (address == null || address.isUnresolved()) {
            JOptionPane.showMessageDialog(dialog, "输入的地址或端口格式错误。", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        var session = new SshSession(address);
        state.addSession(session);

        dialog.dispose();
    }
}
